package 最后24大厂仿真;

import java.util.Stack;

public class FZ3牛牛的字符串解码问题 {

    static class Solution {
        public String decodeString(String s) {
            Stack<Integer> num = new Stack<>();
            Stack<StringBuilder> chs = new Stack<>();
            StringBuilder cur = new StringBuilder();
            int count = 0;
            for (char ch : s.toCharArray()) {
                if (Character.isDigit(ch)) {
                    count = count * 10 + (ch - '0');
                } else if (ch == '[') {
                    num.push(count);
                    chs.push(cur);
                    cur = new StringBuilder();
                    count = 0;
                } else if (ch == ']') {
                    StringBuilder decoded = chs.pop();
                    int times = num.pop();
                    for (int i = 0; i < times; i++) {
                        decoded.append(cur);
                    }
                    cur = decoded;
                }else{
                    cur.append(ch);
                }
            }
            return cur.toString();
        }

    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        // "3[a2[c]]"
        // "abc3[mn]xy"
        System.out.println(solution.decodeString("3[a2[c]]"));
    }
}
